package dao

import (
	"errors"
	"github.com/xormplus/xorm"
	"shoping.zozoo.net/model"
)

type UserInterface interface {
	Create(*model.User) (int64, error)
	FindByUserName(string) (*model.User, error)
}

type UserDao struct {
	*xorm.Engine
}

//获取模型实例
func NewUserDao(orm *xorm.Engine) UserInterface {
	return &UserDao{
		orm,
	}
}

//创建用户
func (u *UserDao) Create(user *model.User) (id int64, err error) {
	if _, err = u.InsertOne(user); err != nil {
		return 0, err
	}

	return user.Id, nil
}

//查找用户
func (u *UserDao) FindByUserName(userName string) (user *model.User, err error) {
	var (
		exist bool
	)

	user = new(model.User)

	if exist, err = u.Where("user_name = ?", userName).Get(user); err != nil {
		return user, err
	}

	if !exist {
		return user, errors.New("用户不存在")
	}

	return user, nil
}
